--[[
	This file is part of FlexBar3.

	FlexBar3 is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	FlexBar3 is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with FlexBar3.  If not, see <http://www.gnu.org/licenses/>.
]]

local Button = FlexBar3:GetModule("Button");
local SecureStateDriverFrame = Button.SecureStateDriverFrame;
local MacroClass = Button:NewButtonClass("AttributeMacro", 1);

function MacroClass:Enable()
	self:RegisterScript("OnUpdate", self.RefreshMacroTexture);
end

function MacroClass:Disable()
	self:UnregisterScript("OnUpdate", self.RefreshMacroTexture);
end

function MacroClass:PlaceMacro(MacroName, StateModifier)
	self:SetModifiedAttribute("type", "macro", StateModifier);
	self:SetModifiedAttribute("type-RightButton", "macro", StateModifier);
	self:SetModifiedAttribute("type-MiddleButton", "macro", StateModifier);
	self:SetModifiedAttribute("macro", MacroName, StateModifier);
	self:SetModifiedAttribute("macro-RightButton", MacroName, StateModifier);
	self:SetModifiedAttribute("macro-MiddleButton", MacroName, StateModifier);
	self:TriggerCallback("ActionChanged");
end

function MacroClass:DragMacroOff()
	local Macro = self:GetModifiedAttribute("Macro");
	if(Macro and Macro ~= "") then
		self:PickupAction("macro", Macro);
		self:SetModifiedAttribute("type", nil);
		self:SetModifiedAttribute("macro", nil);
		local CurrentStateDB = self.StateDB[self:GetModifiedState()];
		CurrentStateDB.Type = nil;
		CurrentStateDB.MacroName = nil;
		self:TriggerCallback("ActionChanged");
	end
end

function MacroClass:RefreshMacroTexture()
	local Macro = self:GetModifiedAttribute("macro");
	if(Macro and Macro ~= "") then
		local _, MacroTexture = GetMacroInfo(Macro);
		if(MacroTexture) then
			self:SetTexture(MacroTexture);
		else
			self:SetTexture([[Interface/Icons/INV_Misc_QuestionMark]]);
		end
	else
		self:SetTexture(nil);
	end
end
